﻿using QRCoder;
using System;
using System.Drawing;
using System.Text;

namespace FineUICoreDesigner.Base
{
    /// <summary>
    /// QR码转字符串
    /// </summary>
    public static class MyQrCode
    {
        /// <summary>
        /// 生成一个QR码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string GenerateQrCodeAscii(string text)
        {
            using (var qrGenerator = new QRCodeGenerator())
            {
                var qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
                using (var qrCode = new QRCode(qrCodeData))
                {
                    using (var qrCodeImage = qrCode.GetGraphic(1))
                    {
                        return ConvertBitmapToAscii(qrCodeImage);
                    }
                }
            }
        }

        private static string ConvertBitmapToAscii(Bitmap bitmap)
        {
            StringBuilder sb = new StringBuilder();
            for (int y = 0; y < bitmap.Height; y++)
            {
                for (int x = 0; x < bitmap.Width; x++)
                {
                    Color pixelColor = bitmap.GetPixel(x, y);
                    sb.Append(pixelColor.R < 128 ? "▇▇" : "  ");
                }
                sb.AppendLine();
            }
            return sb.ToString();
        }
    }
}
